package org.example;

/**
 * key-value 模型的哈希表实现
 */
public class HashBucket {

    static class Node {
        private int key;
        private int value;
        private Node next;

        public Node(int key, int value) {
            this.key = key;
            this.value = value;
        }
    }

    private Node[] array;
    private int usedSize;

    private static final float DEFAULT_LOAD_FACTOR = 0.75f;

    public HashBucket() {
        this.array = new Node[10];
    }

    public void put(int key, int value) {
        Node node = new Node(key, value);
        int index = key % array.length;
        // 看所在位置是不是已经有节点了
        // 有节点就需要遍历到尾节点，看是否要进行value值的更新
        Node cur = array[index];
        while (cur != null) {
            if (cur.key == key) {
                cur.value = value;
                return;
            }
            cur = cur.next;
        }
        // 到这里cur == null,说明index下方的链表没有这个key
        // 采用头插法
        node.next = array[index];
        array[index] = node;
        usedSize++;
        // 计算负载因子
        if (loadFactor() >= DEFAULT_LOAD_FACTOR) {
            resize();
        }

    }

    private void resize() {
        // 2倍扩容
        Node[] newArray = new Node[array.length * 2];
        for (int i = 0; i < array.length; i++) {
            Node cur = array[i];
            while(cur != null) {
                Node curNext = cur.next; // 先保存下一个节点的引用
                int index = cur.key % newArray.length; // 重新计算哈希值，放在新数组的位置
                cur.next = newArray[index];
                newArray[index] = cur;
                // 到这里cur.next和原来的cur已经不再相关了，所以需要一开始就记录后序节点，然后重新赋值
                cur = curNext;
            }
            array = newArray;
        }
    }

    private float loadFactor() {
        return usedSize*1.0f / array.length;
    }

    /**
     * 通过key值 返回value值
     */
    public int get(int key) {
        int index = key % array.length;
        Node cur = array[index];
        while (cur != null) {
            if (cur.key == key) {
                return cur.value;
            }
            cur = cur.next;
        }
        return -1;
    }

}
